import React from 'react';
import ReactEcharts from 'echarts-for-react';
import {connect} from 'dva';
import {Layout, Select, DatePicker, Divider, Button, message, Tabs, Row, Col} from 'antd';
import Gmap from "@/utils/HshMap/Gmap";
import Gkriging from "@/utils/HshMap/Gkriging";
import {FullScreen} from "ol/control";
import EsriJSON from "ol/format/EsriJSON";
import Goverlay from "@/utils/HshMap/Goverlay";
import Ginteraction from "@/utils/HshMap/Ginteraction";
import './index.module.css';
import PublicInterface from "@/utils/Common/PublicInterface";
import styles from './index.less'
// const {RangePicker} = DatePicker;
const {Option} = Select;
const {Header, Content, Sider} = Layout;

const dateFormat = 'YYYY-MM-DD';
@connect(({hydrological}) => ({hydrological}))
class HydrologicalAnalysis extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      birdsUrl: null,
      tableId: null,
      type: 'month',
      selectValue: null,
      monthsButtonType: 'primary',
      yearsButtonType: '',
      dateStr: null,
      endDateStr: null,
      startDateStr: null,
      iconLoading: false,
      width: 1366,
      height: 768,
    };
    this.gmap = new Gmap();
    this.gmap.initMap();
    this.gmap.map.addControl(new FullScreen({tipLabel: '全屏切换'}));
    this.selectOverlay = null;
  }

  getChartsOption = (xdata, rainfall, maxV, minV) => {
    const end = Array.isArray(xdata) && xdata.length > 0 ? 100.0 / (xdata.length / 5.0) : 100;
    const dataZoom = [{
      height: 8,
      bottom: 25,
      start: 0,
      end,
      xAxisIndex: [0],
      filterMode: 'filter'
    }]
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      grid: {
        top: '10%',
        x: 40,
        y: 0
      },
      dataZoom,
      yAxis: {
        type: 'value',
        max: function (value) {
          if (value.max < maxV) {
            return maxV;
          }
          return value.max;
        },
        axisLine: {show: false,},
        axisTick: {show: false},
        splitLine: {show: true, lineStyle: {type: 'dotted', color: '#f2f2f2'}},
        axisLabel: {color: '#545454'}
      },
      xAxis: {
        axisLabel: {
          color: '#545454',
          textStyle: {
            fontSize: '11',
          },
          // interval: 0,
          // rotate: 60
        },
        axisLine: {
          lineStyle: {color: '#bfbfbf'}
        },
        data: xdata,
      },
      series: [
        {
          name: '降水量',
          type: 'bar',
          barCategoryGap: '50%',
          itemStyle: {normal: {color: '#3ec480'}},
          data: rainfall,
          markLine: {
            symbol: "none",               //去掉警戒线最后面的箭头
            label: {
              position: "end"          //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
            },
            data: [
              {
                silent: true,             //鼠标悬停事件  true没有，false有
                name: '高水平线',
                yAxis: maxV,
                label: {
                  formatter: '高',
                },
                lineStyle: {color: 'red'}
              },
              {
                silent: true,             //鼠标悬停事件  true没有，false有
                name: '低水平线',
                yAxis: minV,
                label: {formatter: '低'},
                lineStyle: {color: '#00CC99'}
              },
            ]
          }
        },
      ],
    }
  };

  monthsCount = e => {
    if (this.state.yearsButtonType) {
      this.setState({monthsButtonType: 'primary', yearsButtonType: '', type: 'month'}, async => {
        this.queryRainfall();
      });
    }
  };

  yearsCount = e => {
    if (this.state.monthsButtonType) {
      this.setState({monthsButtonType: '', yearsButtonType: 'primary', type: 'year'}, async => {
        this.queryRainfall();
      });
    }
  };

  selectChange = value => {
    console.log(value)
    this.setState({selectValue: value});

  };

  dataChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState({
      dateStr: dateString
      // startDateStr: dateString[0],
      // endDateStr: dateString[1],
    })
  }

  cancelLoading = () => {
    this.setState({
      iconLoading: false
    })
  }

  buttonOnclick = () => {
    var self = this;
    const {dispatch} = this.props;
    const {selectValue, dateStr, birdsUrl} = this.state;
    // const {selectValue, startDateStr, endDateStr} = this.state;
    self.setState({
      iconLoading: true
    });
    if (!selectValue) {
      self.cancelLoading();
      message.info("请选择监测内容或指标项", 3);
      return;
    }
    var where = ' 1=1 ';
    if (dateStr) {
      var date = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate()+1)).toLocaleDateString().replace(/\//g,'-');
      where += " and datatime >= date '" + dateStr + "' and datatime < date '" + date + "'"
       + " and type = " + selectValue.split(',')[1];
    }
    // if (startDateStr) {
    //   where += " and datatime >= date '" + startDateStr + "' and datatime < date '" + endDateStr + "'";
    // }
    var layerType = birdsUrl;
    var epsG4326Projection = 4326;
    var esrijsonFormat = new EsriJSON();
    dispatch({
      type: 'birdsProject/arcgisFeatureServerQuery',
      payload: {
        where: where,
        type: layerType,
        returnGeometry: true,
        inSR: epsG4326Projection,
        outFields: '*',
        outSR: epsG4326Projection
      },
    }).then(response => {
      if (response.error) {
        self.cancelLoading();
        console.log('服务==>>' + response.error.message + '\n' +
          response.error.details.join('\n'));
      } else {
        // dataProjection will be read from document
        var features = esrijsonFormat.readFeatures(response, {
          featureProjection: 'EPSG:4326'
        });
        if (features.length > 0) {
          Gkriging.krigingImagecanvas(selectValue, this.gmap.map, features, self.cancelLoading());
        } else {
          self.cancelLoading();
          message.info("未查到有效样点，无法插值", 5);
        }
      }
    });

  }

  componentDidMount() {
    this.init();
    this.gmap.map.setTarget('hydrologicalAnalysis');

    // 窗口resize 监听
    this.handleResize();
    window.addEventListener('resize', this.handleResize);

    this.ginteraction = new Ginteraction(this.gmap.map);
    this.ginteraction.on_pointermove(this.select_hover_callback);

    document.addEventListener("fullscreenchange", function (e) {
      var legendClass = document.getElementsByClassName('ol-legend');
      if (document.fullscreenElement) {
        legendClass[0].style.display = 'none';
        console.log('进入全屏')
      } else {
        legendClass[0].style.display = 'block';
        console.log('退出全屏')
      }
    })

  }

  init = () => {
    this.queryRainfall();
    this.queryBaseLine();
    // this.hydrologyNamesQuery();
    this.hydrologyContentQuery()
    var publicInterface = new PublicInterface();
    var self = this;
    //图层列表没有，请求配置服务接口
    publicInterface.mapConfigList(this.props,'水文监测',function (data) {
      if (data && data.data.length > 0) {
        data.data.map(ele => {
          // ele.netUrl = 'http://localhost/';
          if (ele.mapName == '水文监测') {
            self.setState({
              birdsUrl: ele.netUrl + ele.url,
              tableId: ele.tableId
            })
          }
        });
      }
    });
  };
  // 取父div的height
  handleResize = () => {
    const self = this;
    const divWidth = document.body.clientWidth;
    const divHeight = document.body.clientHeight;
    self.setState({width: divWidth, height: divHeight - 66});
    setTimeout(function () {
      self.gmap.map.updateSize();
    }, 100);
  };
  // 查询降水量统计结果
  queryRainfall = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'hydrological/rainfallCount',
      payload: {countType: this.state.type},
    });
  };
  queryBaseLine = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'hydrological/rainfallBaseLine',
      payload: {},
    });
  };

  //检测内容查询
  hydrologyContentQuery = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'hydrological/hydrologyContentQuery',
      payload: {
        "dictKey":"ecology_type"
      },
    });
  };

  selectContentChange = (value) => {
    this.setState({selectValue: ''},()=>{
      this.hydrologyNamesQuery(value)
    });
  }

  //指标项查询
  hydrologyNamesQuery = (value) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'hydrological/hydrologyNamesQuery',
      payload: {
        "dictKey": value
      },
    });
  };

  //hover要素
  select_hover_callback = (e) => {
    if (e.dragging) {
      return;
    }
    var self = this;
    var pupupProperties = {};
    self.clearStyle();
    self.gmap.map.forEachFeatureAtPixel(e.pixel, function (f) {
      self.clearStyle();
      let coodinate = e.coordinate;
      let properties = f.getProperties();
      pupupProperties[self.state.selectValue.split(',')[2]] =  properties.value ? properties.value : '--';
      var overlay = Goverlay.getOverlay_default('hover', coodinate, 1, pupupProperties);
      self.selectOverlay = overlay;
      self.gmap.map.addOverlay(overlay);
    });

  }

  clearStyle = () => {
    var self = this;
    if (self.selectOverlay) {
      self.selectOverlay.setPosition(undefined);
      self.selectOverlay = null;
    }
  }

  render() {
    const {type, monthsButtonType, yearsButtonType} = this.state;
    const {rainfall, baseLine, indexType, indexContent} = this.props.hydrological;
    let selectOptions = indexType.map(ele => {
      return (<Option value={ele.code + "," + ele.dictId + "," + ele.name} key={ele.code}>{ele.name}</Option>)
    });
    let conSelectOptions = indexContent.map(ele => {
      return (<Option value={ele.code} key={ele.code}>{ele.name}</Option>)
    });
    // let defaultVal = (indexType && indexType.length) ? indexType[0].code : '';
    const echartsOption = this.getChartsOption(rainfall.xdata,
      rainfall.rainfall, baseLine[type + '_max'], baseLine[type + '_min']);
    return (
      <Layout>
        <Sider width={371} style={{background: 'rgba(255,255,255,0.9)', padding: '0',borderRight:'1px solid #ddd', position: 'absolute',left: 0,zIndex: 999,height: '300px'}}>
          <div style={{background: '#EBF5EF',height: '40px',lineHeight: '40px',paddingLeft: '20px'}}>
            <span style={{fontSize: '12px',color:'#40AF59'}}>生态插值监测</span>
          </div>
          {/* <div className={styles.showBlock}>
            <h2 style={{color: '#333', fontSize: '12px'}}>降水量统计：
              <Button.Group style={{float: 'right'}}>
                <Button type={monthsButtonType} size={'small'} value="month" onClick={this.monthsCount}>按月</Button>
                <Button type={yearsButtonType} size={'small'} value="year" onClick={this.yearsCount}>按年</Button>
              </Button.Group>
              <span style={{marginRight: '20px'}}>单位：毫米</span>
            </h2>
            <ReactEcharts
              option={echartsOption}
              notMerge={true}
              lazyUpdate={true}
              style={{height: '240px', width: '100%'}}
            />
          </div> */}
          {/* <Divider style={{margin: '5px 0px'}} dashed/> */}
          <div className={styles.showBlock}>
            {/* <h2 style={{color: '#333', fontSize: '12px'}}>生态插值分析：</h2> */}
            <div>
              <Row>
                <Col span={8}>
                  <h3 style={{fontSize: '12px', color: '#333', lineHeight: '38px'}}>监测内容:</h3>
                </Col>
                <Col span={16}>
                    <Select
                      showSearch
                      size={'middle'}
                      style={{width: '100%', fontSize: '12px'}}
                      optionFilterProp="children"
                      onChange={this.selectContentChange}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {conSelectOptions}
                    </Select>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <h3 style={{fontSize: '12px', color: '#333', lineHeight: '38px'}}>选择监测日期:</h3>
                </Col>
                <Col span={16}>
                  <DatePicker format={dateFormat} size={"middle"} onChange={this.dataChange}
                          style={{width: '100%', fontSize: '12px', padding: '5px 0px'}}/>
                </Col>
              </Row>
              <Row style={{marginTop: '10px'}}>
                <Col span={8}>
                  <h3 style={{fontSize: '12px', color: '#333', lineHeight: '32px'}}>选择指标项:</h3>
                </Col>
                <Col span={16}>
                  <Select
                    showSearch
                    size={'middle'}
                    style={{width: '100%', fontSize: '12px'}}
                    optionFilterProp="children"
                    onChange={this.selectChange}
                    value={this.state.selectValue}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {selectOptions}
                  </Select>
                </Col>
              </Row>
            </div>
            <div style={{marginTop: '30px'}}>
              <Button type="primary" size={'middle'} loading={this.state.iconLoading}
                      onClick={this.buttonOnclick} block>
                开始分析
              </Button>
            </div>
          </div>
        </Sider>
        <Layout style={{background: '#fff'}}>
          <Content style={{background: '#eee', padding: '0px', minHeight: 280}}>
            <div id="hydrologicalAnalysis" style={{height: this.state.height}}></div>
          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default HydrologicalAnalysis;
